package com.molyfun.parents.activity.common;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;

import com.molyfun.parents.R;
import com.molyfun.parents.utils.EncryUtils;
import com.molyfun.parents.utils.FileUtils;

import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.exception.ZipException;
import net.lingala.zip4j.progress.ProgressMonitor;

import java.io.File;

import butterknife.ButterKnife;
import butterknife.InjectView;

//import java.util.zip.ZipException;
//import java.util.zip.ZipFile;

public class OfflineGameViewerActivity extends BaseActivity {

    @InjectView(R.id.wv_game)
    WebView webView;
    @InjectView(R.id.bt_game_back)
    ImageView btBack;
    public static final String FLAG_GAME_VIEW_URL_TRANSFER = "game_url";
    private String unPackedFilePath;

    public static void startActivity(Context context, String path){
        Intent intent = new Intent();
        intent.setClass(context, OfflineGameViewerActivity.class);
        intent.putExtra(FLAG_GAME_VIEW_URL_TRANSFER, path);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_game_viewer);
        ButterKnife.inject(this);

        Window window = getWindow();
        if (Build.VERSION.SDK_INT >= 19) {
            int newVis = View.SYSTEM_UI_FLAG_LAYOUT_STABLE

                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION

                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN

                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav bar

                    | View.SYSTEM_UI_FLAG_FULLSCREEN // hide status bar

                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;

            this.getWindow().getDecorView().setSystemUiVisibility(newVis);
        } else {
            window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        }

        String filePath = getIntent().getStringExtra(FLAG_GAME_VIEW_URL_TRANSFER);
        System.out.println("filePath--->" + filePath);
        unPackedFilePath = FileUtils.COURSECACHEPATH + "/" + EncryUtils.md5(filePath) + "/";
        try{
            Unzip(filePath, unPackedFilePath, "molyfun1302",
                    "", handler);
        }catch (ZipException e ){
            e.printStackTrace();
            toast("无法打开游戏");
            finish();
        }

        WebSettings webSettings = webView.getSettings();
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setUseWideViewPort(true);
        webSettings.setJavaScriptEnabled(true);
        webSettings.setBuiltInZoomControls(true);
        webSettings.setDisplayZoomControls(false);
        webSettings.setAllowFileAccess(true);
        webSettings.setAllowFileAccessFromFileURLs(true);
//        webSettings.setMediaPlaybackRequiresUserGesture(false);
        webSettings.setDefaultTextEncodingName("UTF-8");


        webView.setWebChromeClient(new WebChromeClient());
        webView.setWebViewClient(new WebViewClient());
        btBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                OfflineGameViewerActivity.this.finish();
            }
        });

    }

    @Override
    protected void onDestroy() {
        FileUtils.deleteDir(unPackedFilePath);
        super.onDestroy();
    }

    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case CompressStatus.START:
                {
//                    toast("Start...");
                    break;
                }
                case CompressStatus.HANDLING:
                {
                    Bundle bundle=msg.getData();
                    int percent=bundle.getInt(CompressKeys.PERCENT);
//                    toast(percent+"%");
                    break;
                }
                case CompressStatus.ERROR:
                {
                    Bundle bundle=msg.getData();
                    String error=bundle.getString(CompressKeys.ERROR);
                    toast(error);
                    break;
                }
                case CompressStatus.COMPLETED:
                {
                    sendEmptyMessageDelayed(CompressStatus.OPEN_DELAY, 2000);

                    break;
                }
                case CompressStatus.OPEN_DELAY:
                    String webGamePath = "file://" + unPackedFilePath;
                    System.out.println("webGamePath-->" + webGamePath);
                    webView.loadUrl("file://" + unPackedFilePath + "index.html");
                    break;
                default:
                    break;
            }

        };
    };

    public void Unzip(final String zipFilePath, String dest, String passwd,
                             String charset, final Handler handler)
            throws ZipException {
        ZipFile zFile = null;
        try {
            zFile = new ZipFile(new File(zipFilePath));
        } catch (Exception e) {
            throw new ZipException("no file");
        }
        if (TextUtils.isEmpty(charset)) {
            charset = "GBK";
        }
        zFile.setFileNameCharset(charset);
        if (!zFile.isValidZipFile()) {
            throw new ZipException(
                    "Compressed files are not illegal, may be damaged.");
        }
        File destDir = new File(dest); // Unzip directory
        if (destDir.isDirectory() && !destDir.exists()) {
            destDir.mkdir();
        }
        if (zFile.isEncrypted()) {
            zFile.setPassword(passwd.toCharArray());
        }

        final ProgressMonitor progressMonitor = zFile.getProgressMonitor();

        Thread progressThread = new Thread(new Runnable() {

            @Override
            public void run() {
                Bundle bundle = null;
                Message msg = null;
                try {
                    int percentDone = 0;
                    // long workCompleted=0;
                    // handler.sendEmptyMessage(ProgressMonitor.RESULT_SUCCESS)
                    if (handler == null) {
                        return;
                    }
                    handler.sendEmptyMessage(CompressStatus.START);
                    while (true) {
                        Thread.sleep(50);

                        percentDone = progressMonitor.getPercentDone();
                        bundle = new Bundle();
                        bundle.putInt(CompressKeys.PERCENT, percentDone);
                        msg = new Message();
                        msg.what = CompressStatus.HANDLING;
                        msg.setData(bundle);
                        handler.sendMessage(msg);
                        if (percentDone >= 100 || progressMonitor.getTotalWork() == 0l) {
                            break;
                        }
                    }
                    handler.sendEmptyMessage(CompressStatus.COMPLETED);
                } catch (InterruptedException e) {
                    bundle = new Bundle();
                    bundle.putString(CompressKeys.ERROR, e.getMessage());
                    msg = new Message();
                    msg.what = CompressStatus.ERROR;
                    msg.setData(bundle);
                    handler.sendMessage(msg);
                    e.printStackTrace();
                }
            }
        });

        progressThread.start();
        zFile.setRunInThread(true);
        zFile.extractAll(dest);
    }

    public interface CompressStatus {
        public final static int START=0;
        public final static int HANDLING=1;
        public final static int COMPLETED=2;
        public final static int ERROR=3;
        public final static int OPEN_DELAY=4;
    }

    public interface CompressKeys {
        public final static String PERCENT="PERCENT";
        public final static String ERROR="ERROR";
    }

}